import { createWebHistory, createRouter } from 'vue-router'

import Test from '@/views/Test.vue'
import Login from '@/views/Login.vue'
import Index from '@/views/Index.vue'
import Add from '@/views/Add.vue'
import Update from '@/views/Update.vue'
import LineChart from '@/views/LineChart.vue'
import Nav from '@/views/Nav.vue'

const routes = [
    {
        path: '/',
        component: Nav,
        children: [
            { path: 'index', component: Index },
            { path: 'test', component: Test },
            { path: 'add', component: Add },
            { path: 'update', component: Update },
            { path: 'lineChart', component: LineChart },
        ]
    },
    { path: '/login', component: Login },

]

export const router = createRouter({
    history: createWebHistory(),
    routes,
})

//加路由守卫
router.beforeEach((to, from, next) => {
    if (to.path === '/login') {
        localStorage.removeItem('token')
        next()
    } else {
        const token = localStorage.getItem('token')
        if (token) {
            const payload = JSON.parse(atob(token.split('.')[1]));
            if (payload.exp * 1000 > Date.now()) {
                next()
            } else {
                localStorage.removeItem('token')
                next('/login')
            }
        } else {
            localStorage.removeItem('token')
            next('/login')
        }
    }
})

export default router
